package com.xhtt.modules.inspection.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.exception.RRExceptionEnum;
import com.xhtt.common.utils.*;
import com.xhtt.modules.inspection.dao.InsTaskStepMapper;
import com.xhtt.modules.inspection.dto.InspectionAppDTO;
import com.xhtt.modules.inspection.entity.*;
import com.xhtt.modules.inspection.enums.*;
import com.xhtt.modules.inspection.schedule.InsMsgEntity;
import com.xhtt.modules.inspection.service.*;
import com.xhtt.modules.inspection.util.InspectDateUtil;
import com.xhtt.modules.inspection.vo.TaskCompositeVO;
import com.xhtt.modules.sys.entity.SysUserDeptEntity;
import com.xhtt.modules.sys.entity.SysUserEntity;
import com.xhtt.modules.sys.service.SysDeptService;
import com.xhtt.modules.sys.service.SysUserDeptService;
import com.xhtt.modules.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 巡检-每次任务
 * </p>
 *
 * @author xj
 * @since 2019-01-29
 */
@Service
@Slf4j
public class InsTaskStepServiceImpl extends ServiceImpl<InsTaskStepMapper, InsTaskStep> implements IInsTaskStepService {

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserDeptService sysUserDeptService;

    @Autowired
    private IInsTaskService insTaskService;

    @Autowired
    private IInsTaskDateService insTaskDateService;

    @Autowired
    private IInsTaskUserService insTaskUserService;

    @Autowired
    private IInsTaskStepPointService insTaskStepPointService;

    @Autowired
    private IInsPointSubitemService insPointSubService;

    @Autowired
    private IInsClassesTeamDetailService insClassesTeamDetailService;


    @Override
    public List<InsTaskStep> addDay(List<List<LocalDateTime>> stepResults, InsTask insTask, int type) {

        String step = UUID.randomUUID().toString();
        Integer taskId = insTask.getId();

        List<InsTaskStep> insTaskSteps = new ArrayList<>();
        InsTaskStep insTaskStep;

        for (List<LocalDateTime> e : stepResults) {

            // 获取开始时间
            LocalDateTime start = e.get(0).withHour(0).withMinute(0).withSecond(0);

            // 日期是今天并且有数据则直接跳出循环
            if (start.equals(DateUtils.now())) {
                // 如果今天有数据的不进行覆盖
                List<InsTaskStep> taskSteps = this
                        .list(new LambdaQueryWrapper<InsTaskStep>()
                                .eq(InsTaskStep::getTaskId, taskId)
                                .eq(InsTaskStep::getTaskStartDate, DateUtils.now())
//                            .eq(InsTaskStep::getPushed, InsPushEnum.Y.getCode())
                                .eq(InsTaskStep::getShiftType, type));

                if (CollectionUtils.isNotEmpty(taskSteps)) {
                    return null;
                }
            }

            insTaskStep = new InsTaskStep();
            // 开始结束不一样
            insTaskStep.setTaskStartDate(e.get(0).withHour(0).withMinute(0).withSecond(0));
            insTaskStep.setTaskEndDate(e.get(e.size() - 1).withHour(0).withMinute(0).withSecond(0));
            insTaskStep.setTaskId(taskId);
            insTaskStep.setStep(step);
            insTaskStep.setTaskName(insTask.getTaskName());
            insTaskStep.setInspectRate(insTask.getInspectRate());
            if (type == 1) {
                insTaskStep.setInspectMorningStartDate(e.get(0));
                insTaskStep.setInspectMorningEndDate(e.get(e.size() - 1));
                insTaskStep.setShiftType(1);
                insTaskStep.setMorningStartDate(insTask.getInspectMorningStartDate());
                insTaskStep.setMorningEndDate(insTask.getInspectMorningEndDate());
            } else {
                insTaskStep.setInspectNightStartDate(e.get(0));
                insTaskStep.setInspectNightEndDate(e.get(e.size() - 1));
                insTaskStep.setShiftType(2);
                insTaskStep.setNightStartDate(insTask.getInspectNightStartDate());
                insTaskStep.setNightEndDate(insTask.getInspectNightEndDate());
            }
            insTaskSteps.add(insTaskStep);
        }
        this.saveBatch(insTaskSteps);
        return insTaskSteps;
    }

    @Override
    public List<InsTaskStep> addWeekOrMonth(List<List<LocalDateTime>> stepResults, InsTask insTask) {

        InsTaskStep insTaskStep;
        String step;
        List<InsTaskStep> insTaskSteps = new ArrayList<>();

        Integer taskId = insTask.getId();
        Integer inspectType = insTask.getInspectType();
        // 巡检类型 这里需要区分周巡检和月巡检
//        Integer inspectType = insTask.getInspectType();

        /*
         * 获取已经推送的数据集合
         */
//        List<InsTaskStep> insTaskSteps1 = this
//                .list(new LambdaQueryWrapper<InsTaskStep>()
//                        .eq(InsTaskStep::getTaskId, taskId)
//                        .eq(InsTaskStep::getPushed, InsPushEnum.Y.getCode())
//                        .groupBy(InsTaskStep::getStep));

        for (List<LocalDateTime> e : stepResults) {
            // 待添加开始时间
            LocalDateTime start = e.get(0);
            // 待添加结束日期
            LocalDateTime end = e.get(e.size() - 1);

            List<LocalDateTime> weekDate = InspectDateUtil.getCurrentWeek(start);

            List<LocalDateTime> monthDate = InspectDateUtil.getCurrentMonth(start);

            if (inspectType.equals(InspectTypeEnum.WEEK.getCode())) {
                List<InsTaskStep> insTaskStepsWeek = baseMapper
                        .selectList(new LambdaQueryWrapper<InsTaskStep>()
                                .eq(InsTaskStep::getTaskId, taskId)
                                .ge(InsTaskStep::getTaskStartDate, weekDate.get(0))
                                .le(InsTaskStep::getTaskEndDate, weekDate.get(1)));
                if (CollectionUtils.isNotEmpty(insTaskStepsWeek)) {
                    return null;
                }
            } else if (inspectType.equals(InspectTypeEnum.MONTH.getCode())) {
                List<InsTaskStep> insTaskStepsMonth = baseMapper
                        .selectList(new LambdaQueryWrapper<InsTaskStep>()
                                .eq(InsTaskStep::getTaskId, taskId)
                                .le(InsTaskStep::getTaskEndDate, monthDate.get(1))
                                .ge(InsTaskStep::getTaskStartDate, monthDate.get(0)));
                if (CollectionUtils.isNotEmpty(insTaskStepsMonth)) {
                    return null;
                }
            }
            step = UUID.randomUUID().toString();

            for (int i = 0; i < insTask.getInspectRate(); i++) {
                insTaskStep = new InsTaskStep();
                BeanUtils.copyProperties(insTask, insTaskStep);
                insTaskStep.setId(null);
                insTaskStep.setTaskId(taskId);
                insTaskStep.setStep(step);
                insTaskStep.setTaskStartDate(start);
                insTaskStep.setTaskEndDate(end);

                // 设置冗余字段
                insTaskStep.setTaskName(insTask.getTaskName());
                insTaskStep.setInspectRate(insTask.getInspectRate());
                insTaskStep.setMorningStartDate(insTask.getInspectMorningStartDate());
                insTaskStep.setMorningEndDate(insTask.getInspectMorningEndDate());
                insTaskStep.setNightStartDate(insTask.getInspectNightStartDate());
                insTaskStep.setNightEndDate(insTask.getInspectNightEndDate());

                insTaskSteps.add(insTaskStep);
            }
        }
        this.saveBatch(insTaskSteps);
        return insTaskSteps;
    }


    /**
     * 判断任务分配中是否有这个人
     *
     * @param userId 当前登录的人
     * @return
     */
    @Override
    public boolean taskIsIncludeUser(Integer userId, Integer taskStepId) {
        List<InsTaskUser> insTaskUsers = insTaskUserService
                .list(new LambdaQueryWrapper<InsTaskUser>()
                        .eq(InsTaskUser::getUserId, userId)
                        .eq(InsTaskUser::getTaskStepId, taskStepId));

        return CollectionUtils.isNotEmpty(insTaskUsers);
    }

    /**
     * 替换年月日
     *
     * @return
     */
    private LocalDateTime replaceDate(LocalDateTime pattern, LocalDateTime source) {

        return source.withYear(pattern.getYear()).withMonth(pattern.getMonthValue()).withDayOfMonth(pattern.getDayOfMonth());

    }

    /**
     * 现场巡检日巡检查询,前一次任务结束时间是下一次任务开始时间,如果下一次没有任务上一次的任务就会一直存在
     *
     * @param userId
     * @return
     */
    @Override
    public List<InspectionAppDTO> queryDayList(Integer userId) {

        // 根据巡检类型获取任务
        List<InsTask> insTasks = insTaskService.getAllByInspectType(InspectTypeEnum.DAY.getCode());

        InspectionAppDTO insTaskStep;

        List<InspectionAppDTO> result = new ArrayList<>();

        for (InsTask insTask : insTasks) {

            Integer taskId = insTask.getId();

            // 获取任务属于那个组
//            Integer teamId = insTask.getTeamId();

            // 获取当天排班情况
//            InsClassesTeamDetail insClassesTeamDetail = insClassesTeamDetailService.getByNow();

            // 查看日班还是夜班
//            int shift = teamId.equals(insClassesTeamDetail.getTeamMorning()) ? 1 : 2;

            // 当前时间
            LocalDateTime now = LocalDateTime.now();

            insTaskStep = new InspectionAppDTO();
            BeanUtils.copyProperties(insTask, insTaskStep);

            List<InsTaskStep> insTaskSteps = new ArrayList<>();

            // 获取今天的任务
            List<InsTaskStep> insTaskStepTemp = baseMapper.queryDayList(now, taskId);

            // 如果今天任务为空就去找上一次任务
            if (CollectionUtils.isEmpty(insTaskStepTemp)) {
                // 获取任务时间段内 前一个排班的日期
                InsClassesTeamDetail insClassesTeamDetailAgo = insClassesTeamDetailService.getAgoByTaskId(taskId);
                if (insClassesTeamDetailAgo != null) {
                    LocalDateTime time = insClassesTeamDetailAgo.getDate();

                    // 根据排班日期查询上一次任务,时分秒设置最大,保证能够查到当天的数据
                    insTaskStepTemp = baseMapper.queryDayList(time.withHour(23).withMinute(59).withSecond(59), taskId);
//                    log.error("执行时的时间是 : {}", time.withHour(23).withMinute(59).withSecond(59));
//                    log.error("任务id : {}, 循环结果是 : {}", insTask.getId(), l);
                    now = now.withHour(23).withMinute(59).withSecond(59);
                }
            }

            // 现在时间加上15分钟
            LocalDateTime nowAddFifteen = now.plusMinutes(15);

            final LocalDateTime finalNow = now;

            if (CollectionUtils.isNotEmpty(insTaskStepTemp)) {
                InsTaskStep insTaskStepMain = insTaskStepTemp.get(0);
                Integer taskStepId = insTaskStepMain.getId();

                // 存在这个人时添加数据 , 组长不需要看到任务
                if (taskIsIncludeUser(userId, taskStepId)/* || insTask.getCreateUserId().equals(userId)*/) {

                    // 查询出相同step的数据(代表同一天数据)
                    List<InsTaskStep> insTaskStepList = baseMapper
                            .selectList(new LambdaQueryWrapper<InsTaskStep>()
                                    .eq(InsTaskStep::getStep, insTaskStepMain.getStep())
                                    .orderByAsc(InsTaskStep::getTaskStartDate, InsTaskStep::getInspectMorningStartDate, InsTaskStep::getInspectNightStartDate));

                    /*
                     * 提前15分钟后进行筛选
                     * 判断该任务状态
                     * 开始时间小于当前时间
                     * 结束时间大于当前时间(暂时不做判断,前一个任务未完成,下一个任务无法开始)
                     */
                    insTaskStepList.forEach(e -> {

                        // 获取早晚班时间段
                        LocalDateTime mornStart = e.getInspectMorningStartDate();
                        LocalDateTime mornEnd = e.getInspectMorningEndDate();
                        LocalDateTime nightStart = e.getInspectNightStartDate();
                        LocalDateTime nightEnd = e.getInspectNightEndDate();

                        // 未巡检不需要判断结束时间
                        if (e.getStatus().equals(InspectStepStatusEnum.CREATE.getCode())) {
                            if (e.getShiftType() == 1) {
                                if (mornStart != null && mornEnd != null) {
                                    if (mornStart.isBefore(nowAddFifteen)) {
                                        e.setTaskStartDate(e.getMorningStartDate());
                                        e.setTaskEndDate(e.getMorningEndDate());
                                        insTaskSteps.add(e);
                                    }
                                }
                            } else if (e.getShiftType() == 2) {
                                if (nightStart != null && nightEnd != null) {
                                    if (nightStart.isBefore(nowAddFifteen)) {
                                        e.setTaskStartDate(e.getNightStartDate());
                                        e.setTaskEndDate(e.getNightEndDate());
                                        insTaskSteps.add(e);
                                    }
                                }
                            }
                        } else if (e.getStatus().equals(InspectStepStatusEnum.FINISH.getCode())) {
                            if (e.getShiftType() == 1) {
                                if (mornStart != null && mornEnd != null) {
                                    if (mornEnd.isAfter(finalNow) && mornStart.isBefore(nowAddFifteen)) {
                                        e.setTaskStartDate(e.getMorningStartDate());
                                        e.setTaskEndDate(e.getMorningEndDate());
                                        insTaskSteps.add(e);
                                    }
                                }
                            } else if (e.getShiftType() == 2) {
                                if (nightStart != null && nightEnd != null) {
                                    if (nightStart.isBefore(nowAddFifteen) && nightEnd.isAfter(finalNow)) {
                                        e.setTaskStartDate(e.getNightStartDate());
                                        e.setTaskEndDate(e.getNightEndDate());
                                        insTaskSteps.add(e);
                                    }
                                }
                            }
                        }
                    });

                    if (CollectionUtils.isNotEmpty(insTaskSteps)) {

                        // 获取已巡检次数
                        List<InsTaskStep> insTaskStepsFinish = insTaskStepList.stream()
                                .filter(e -> e.getStatus().equals(InspectStepStatusEnum.FINISH.getCode()))
                                .collect(Collectors.toList());

                        // 获取未巡检次数
                        List<InsTaskStep> insTaskStepsCreate = insTaskStepList.stream()
                                .filter(e -> e.getStatus().equals(InspectStepStatusEnum.CREATE.getCode()))
                                .collect(Collectors.toList());

                        if (CollectionUtils.isNotEmpty(insTaskStepsCreate)) {
                            // 获取当前执行的那一条
                            InsTaskStep curTaskStep = insTaskSteps.get(0);

                            if (curTaskStep != null) {

                                // 设置是否可以点击
                                if (insTaskStep.getDisable() == null) {
                                    insTaskStep.setDisable(isBelong(curTaskStep.getId(), userId));
                                    if (curTaskStep.getStatus().equals(InspectStepStatusEnum.FINISH.getCode())) {
                                        insTaskStep.setDisable(1);
                                    }
                                }

                                // 当前执行的任务，没有开始执行时间，任务状态又是巡检中，则设置为待巡检状态
                                if (curTaskStep.getExecStartDate() == null && insTaskStep.getTaskStatus().equals(TaskStatusEnum.START.getCode())) {
                                    insTaskStep.setTaskStatus(TaskStatusEnum.CREATE.getCode());
                                }
//                                // 如果前一天的任务未完成，第二天设置为待巡检状态
//                                if (curTaskStep.getStatus().equals(InspectStepStatusEnum.CREATE.getCode())) {
//                                    insTaskStep.setTaskStatus(curTaskStep.getStatus());
//                                }

                                insTaskStep.setTaskStepId(curTaskStep.getId());

                                // 巡检时间段
                                insTaskStep.setTaskStartDate(curTaskStep.getTaskStartDate());
                                insTaskStep.setTaskEndDate(curTaskStep.getTaskEndDate());

                                insTaskStep.setTaskName(curTaskStep.getTaskName());
                            }

                            insTaskStep.setTotalStep(insTaskStepList.size());
                            insTaskStep.setCurrentStep(insTaskStepsFinish.size());

                            result.add(insTaskStep);
                        } else {
                            if (CollectionUtils.isNotEmpty(insTaskStepsFinish)) {
                                // 全部完成
                                InsTaskStep insTaskStepFinishItem = insTaskStepsFinish.get(insTaskStepsFinish.size() - 1);
                                // 全部执行完成后,总次数和已完成次数设置一样的
                                insTaskStep.setTotalStep(insTaskStepsFinish.size());
                                insTaskStep.setCurrentStep(insTaskStepsFinish.size());
                                insTaskStep.setTaskStartDate(insTaskStepFinishItem.getShiftType() == 1 ? insTaskStepFinishItem.getInspectMorningStartDate() : insTaskStepFinishItem.getInspectNightStartDate());
                                insTaskStep.setTaskEndDate(insTaskStepFinishItem.getShiftType() == 1 ? insTaskStepFinishItem.getInspectMorningEndDate() : insTaskStepFinishItem.getInspectNightEndDate());
                                insTaskStep.setTaskStatus(TaskStatusEnum.FINISH.getCode());
                                insTaskStep.setDisable(1);
                                result.add(insTaskStep);
                            }
                        }
                    }
                }
            }
        }
        return result;
    }

    @Override
    public List<InspectionAppDTO> queryWeekList(Integer userId) {

        List<InspectionAppDTO> result = new ArrayList<>();

        InspectionAppDTO insTaskStep;

        // 根据巡检类型获取任务
        List<InsTask> insTasks = insTaskService.getAllByInspectType(InspectTypeEnum.WEEK.getCode());

        for (InsTask insTask : insTasks) {

            Integer taskId = insTask.getId();

            // List<LocalDateTime> localDateTimes = InspectDateUtil.getCurrentWeek();
            insTaskStep = new InspectionAppDTO();
            BeanUtils.copyProperties(insTask, insTaskStep);

            List<InsTaskStep> insTaskSteps = baseMapper
                    .selectList(new LambdaQueryWrapper<InsTaskStep>()
                            .eq(InsTaskStep::getTaskId, taskId)
                            .ge(InsTaskStep::getTaskEndDate, DateUtils.now())
                            .le(InsTaskStep::getTaskStartDate, DateUtils.now())
                            .eq(InsTaskStep::getPushed, InsPushEnum.Y.getCode())
//                                .le(InsTaskStep::getTaskStartDate, localDateTimes.get(0))
//                                .le(InsTaskStep::getTaskEndDate, localDateTimes.get(1))
                            .orderByAsc(InsTaskStep::getTaskStartDate, InsTaskStep::getInspectMorningStartDate, InsTaskStep::getInspectNightStartDate));


            if (CollectionUtils.isNotEmpty(insTaskSteps)) {

                Integer taskStepId = insTaskSteps.get(0).getId();
                if (taskIsIncludeUser(userId, taskStepId)/* || insTask.getCreateUserId().equals(userId)*/) {

                    // 已巡检次数
                    List<InsTaskStep> insTaskStepsFinish = insTaskSteps.stream()
                            .filter(e -> e.getStatus().equals(InspectStepStatusEnum.FINISH.getCode()))
                            .collect(Collectors.toList());

                    // 获取未巡检次数
                    List<InsTaskStep> insTaskStepsCreate = insTaskSteps.stream()
                            .filter(e -> e.getStatus().equals(InspectStepStatusEnum.CREATE.getCode()))
                            .collect(Collectors.toList());

                    if (CollectionUtils.isNotEmpty(insTaskStepsCreate)) {
                        // 获取当前执行的那一条
                        InsTaskStep curTaskStep = insTaskStepsCreate.get(0);
                        if (curTaskStep != null) {

                            // 当前执行的任务，没有开始执行时间，任务状态又是巡检中，则设置为待巡检状态
                            if (curTaskStep.getExecStartDate() == null && insTaskStep.getTaskStatus().equals(TaskStatusEnum.START.getCode())) {
                                insTaskStep.setTaskStatus(TaskStatusEnum.CREATE.getCode());
                            }

                            // 设置是否可以点击
                            insTaskStep.setDisable(isBelong(curTaskStep.getId(), userId));
                            insTaskStep.setTaskStepId(curTaskStep.getId());
                            insTaskStep.setTaskName(curTaskStep.getTaskName());
                            insTaskStep.setInspectMorningStartDate(curTaskStep.getMorningStartDate());
                            insTaskStep.setInspectMorningEndDate(curTaskStep.getMorningEndDate());
                            insTaskStep.setInspectNightStartDate(curTaskStep.getNightStartDate());
                            insTaskStep.setInspectNightEndDate(curTaskStep.getNightEndDate());
                        }

                        insTaskStep.setTotalStep(insTaskSteps.size());
                        insTaskStep.setCurrentStep(insTaskStepsFinish.size());
//                    insTaskStep.setCurrentStep(insTaskSteps2.size() + 1);

                        result.add(insTaskStep);
                    } else {
                        if (CollectionUtils.isNotEmpty(insTaskStepsFinish)) {
                            // 全部执行完成后,总次数和已完成次数设置一样的
                            insTaskStep.setTotalStep(insTaskSteps.size());
                            insTaskStep.setCurrentStep(insTaskSteps.size());
                            insTaskStep.setTaskStatus(TaskStatusEnum.FINISH.getCode());
                            insTaskStep.setDisable(1);
                            result.add(insTaskStep);
                        }

                    }
                }
            }
        }
        return result;
    }

    @Override
    public List<InspectionAppDTO> queryMonthList(Integer userId) {

        List<InspectionAppDTO> result = new ArrayList<>();

        InspectionAppDTO insTaskStep;

        // 根据巡检类型获取任务
        List<InsTask> insTasks = insTaskService.getAllByInspectType(InspectTypeEnum.MONTH.getCode());

        for (InsTask insTask : insTasks) {

            Integer taskId = insTask.getId();

            //                List<LocalDateTime> localDateTimes = InspectDateUtil.getCurrentMonth();

            insTaskStep = new InspectionAppDTO();

            BeanUtils.copyProperties(insTask, insTaskStep);

            List<InsTaskStep> insTaskSteps = baseMapper
                    .selectList(new LambdaQueryWrapper<InsTaskStep>()
                            .eq(InsTaskStep::getTaskId, taskId)
                            .ge(InsTaskStep::getTaskEndDate, DateUtils.now())
                            .le(InsTaskStep::getTaskStartDate, DateUtils.now())
                            .eq(InsTaskStep::getPushed, InsPushEnum.Y.getCode())
//                                .ge(InsTaskStep::getTaskStartDate, localDateTimes.get(0))
//                                .le(InsTaskStep::getTaskEndDate, localDateTimes.get(1))
                            .orderByAsc(InsTaskStep::getTaskStartDate, InsTaskStep::getInspectMorningStartDate, InsTaskStep::getInspectNightStartDate));

            if (CollectionUtils.isNotEmpty(insTaskSteps)) {

                Integer taskStepId = insTaskSteps.get(0).getId();

                if (taskIsIncludeUser(userId, taskStepId)/* || insTask.getCreateUserId().equals(userId)*/) {

                    // 已巡检次数
                    List<InsTaskStep> insTaskStepsFinish = insTaskSteps.stream()
                            .filter(e -> e.getStatus().equals(InspectStepStatusEnum.FINISH.getCode()))
                            .collect(Collectors.toList());

                    // 获取未巡检次数
                    List<InsTaskStep> insTaskStepsCreate = insTaskSteps.stream()
                            .filter(e -> e.getStatus().equals(InspectStepStatusEnum.CREATE.getCode()))
                            .collect(Collectors.toList());

                    if (CollectionUtils.isNotEmpty(insTaskStepsCreate)) {
                        // 获取当前执行的那一条
                        InsTaskStep curTaskStep = insTaskStepsCreate.get(0);

                        if (curTaskStep != null) {

                            // 当前执行的任务，没有开始执行时间，任务状态又是巡检中，则设置为待巡检状态
                            if (curTaskStep.getExecStartDate() == null && insTaskStep.getTaskStatus().equals(TaskStatusEnum.START.getCode())) {
                                insTaskStep.setTaskStatus(TaskStatusEnum.CREATE.getCode());
                            }

                            // 设置是否可以点击
                            insTaskStep.setDisable(isBelong(curTaskStep.getId(), userId));
                            insTaskStep.setTaskStepId(curTaskStep.getId());
                            insTaskStep.setTaskName(curTaskStep.getTaskName());

                            insTaskStep.setInspectNightStartDate(curTaskStep.getNightStartDate());
                            insTaskStep.setInspectNightEndDate(curTaskStep.getNightEndDate());
                            insTaskStep.setInspectMorningStartDate(curTaskStep.getMorningStartDate());
                            insTaskStep.setInspectMorningEndDate(curTaskStep.getMorningEndDate());
                        }

                        insTaskStep.setCurrentStep(insTaskStepsFinish.size());
//                    insTaskStep.setCurrentStep(insTaskSteps2.size() + 1);
                        insTaskStep.setTotalStep(insTaskSteps.size());

                        result.add(insTaskStep);
                    } else {
                        if (!CollectionUtils.isEmpty(insTaskStepsFinish)) {
                            // 全部执行完成后,总次数和已完成次数设置一样的
                            insTaskStep.setTotalStep(insTaskSteps.size());
                            insTaskStep.setCurrentStep(insTaskSteps.size());
                            insTaskStep.setDisable(1);
                            insTaskStep.setTaskStatus(TaskStatusEnum.FINISH.getCode());
                            result.add(insTaskStep);
                        }
                    }

                }
            }
        }

        return result;
    }

    @Override
    public PageUtils queryPageIsFinish(Map<String, Object> params) {

//        SysUserEntity user = (SysUserEntity) params.get("user");
//
//        if (Optional.ofNullable(params.get("ids")).isPresent()) {
//            String idStr = params.get("ids").toString();
//            String[] ids = idStr.split(",");
//            params.put("ids", Arrays.asList(ids));
//        }
//
//        // 是否拼接userIds 以及是否拼接deptId
//        boolean isTeamLeader = false;
//
//        // 先添加当前用户
//        List<Integer> userIds = new ArrayList<>();
//        userIds.add(user.getUserId().intValue());
//
//        // 判断是不是管理员
//        boolean isSuper = user.getUserId() == Constant.SUPER_ADMIN;
//
//        if (isSuper) {
//            List<SysUserDeptEntity> sysUserDeptEntities = sysUserDeptService.list();
//            userIds = sysUserDeptEntities.stream().map(e -> e.getUserId().intValue()).collect(Collectors.toList());
//        } else {
//            Integer deptId = user.getTeamId();
//            if (deptId != null) {
//
//                // 组长
//                if (user.getRoleName().equals("Key User")) {
//                    isTeamLeader = true;
//                    List<SysUserEntity> sysUserEntityList = sysUserService.list(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getTeamId, deptId));
//                    if (CollectionUtils.isNotEmpty(sysUserEntityList)) {
//                        userIds = sysUserEntityList.stream().map(e -> e.getUserId().intValue()).collect(Collectors.toList());
//                    }
//                    params.put("teamId", deptId);
//                }
//            } else {
//                // 部门管理员
//                if (user.getRoleName().equals("Expert User")) {
//                    // 获取该部门下所有子部门
//                    List<String> dept = sysDeptService.getChildDept(Integer.parseInt(user.getDeptId()));
//                    List<SysUserDeptEntity> sysUserDeptEntities = sysUserDeptService
//                            .list(new LambdaQueryWrapper<SysUserDeptEntity>()
//                                    .in(SysUserDeptEntity::getDeptId, dept));
//                    userIds = sysUserDeptEntities.stream().map(e -> e.getUserId().intValue()).collect(Collectors.toList());
//                }
//            }
//        }
//
//        params.put("userIds", userIds);
//        params.put("isTeamLeader", isTeamLeader);

        Page<TaskCompositeVO> page = new Query<TaskCompositeVO>(params).getPage();
        List<TaskCompositeVO> taskCompositeVOS = baseMapper.queryPage(page, params);
        taskCompositeVOS.forEach(e -> {

            List<InsTaskStepPoint> insTaskStepPoints = insTaskStepPointService
                    .list(new LambdaQueryWrapper<InsTaskStepPoint>()
                            .eq(InsTaskStepPoint::getTaskStepId, e.getTaskStepId())
                            .orderByAsc(InsTaskStepPoint::getCreateTime));
            if (CollectionUtils.isNotEmpty(insTaskStepPoints)) {
                // 获取未签到列表
                List<InsTaskStepPoint> insTaskStepPointNoSignList = insTaskStepPoints.stream()
                        .filter(m -> m.getIsSign().equals(SignEnum.NO.getCode())).collect(Collectors.toList());
                if (insTaskStepPointNoSignList.size() <= 0) {
                    e.setIsSign("无");
                } else {
                    e.setIsSign("有");
                }
            }
            // 数字转化成对应的中文
            if (e.getLineType() != null) {
                e.setLineType(EnumUtils.getMsgByCode(LineTypeEnum.class, Integer.parseInt(e.getLineType())).getMsg());
            }
            if (e.getInspectType() != null) {
                e.setInspectType(EnumUtils.getMsgByCode(InspectTypeEnum.class, Integer.parseInt(e.getInspectType())).getMsg());
            }
        });
        page.setRecords(taskCompositeVOS);
        return new PageUtils(page);
    }

    @Override
    public void exportExcel(HttpServletResponse response, Map<String, Object> params) {

        ExportExcel exportExcel = new ExportExcel();

        params.put("limit", "65000");

        PageUtils pageUtils = queryPageIsFinish(params);
        List list = pageUtils.getList();
        String fileName = "现场巡检记录";
        String sheetName = "sheet1";
        String[] headers = {"巡检时间", "任务名称", "线路类型", "巡检类型", "巡检时间段", "巡检班组", "巡检人员", "有无未签到"};
        String[] columns = {"datetime", "taskName", "lineType", "inspectType", "insDate", "teamName", "executor", "isSign"};
        try {
            exportExcel.exportExcel(fileName, sheetName, headers, columns, list, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(RRExceptionEnum.EXPORT_FAIL);
        }
    }


    /**
     * 获取子任务已经完成的检点id集合
     *
     * @param stepId
     * @return
     */
    @Override
    public Set<Integer> getTaskStepPointChecked(Integer stepId) {
        // 查询子任务对应的记录
        List<InsTaskStepPoint> insTaskStepPoints = insTaskStepPointService.list(new LambdaQueryWrapper<InsTaskStepPoint>().eq(InsTaskStepPoint::getTaskStepId, stepId));

        if (CollectionUtils.isNotEmpty(insTaskStepPoints)) {
            // 查询巡检内容
            List<Integer> insPointSubIds = insTaskStepPoints.stream().map(InsTaskStepPoint::getPointSubitemId).collect(Collectors.toList());

            List<InsPointSubitem> insPointSubs1 = new ArrayList<>();

            // 根据巡检内容查询检点id
            for (Integer insPointSubId : insPointSubIds) {
                InsPointSubitem insPointSubitem = insPointSubService.getAllById(insPointSubId);
                if (insPointSubitem != null) {
                    insPointSubs1.add(insPointSubitem);
                }
            }
            // 获取已巡检的检点id集合
            return insPointSubs1.stream().map(InsPointSubitem::getPointId).collect(Collectors.toSet());
        }
        return new HashSet<>();
    }

    /**
     * 根据当前日期和巡检类型获取子任务数据
     * 日巡检  当天所有子任务各时间段集合
     * 周巡检  当前周的所有子任务集合
     * 月巡检  当前月的所有子任务集合
     *
     * @param taskId 任务id
     * @return List<InsTaskStep>
     */
    @Override
    public List<InsTaskStep> getTaskStepList(Integer taskId) {

        InsTask insTask = insTaskService.getById(taskId);

        List<InsTaskStep> insTaskSteps = new ArrayList<>();

        if (insTask != null) {
            Integer inspectType = insTask.getInspectType();

            if (inspectType.equals(InspectTypeEnum.DAY.getCode())) {
                insTaskSteps = baseMapper
                        .selectList(new LambdaQueryWrapper<InsTaskStep>()
                                .eq(InsTaskStep::getTaskId, taskId)
                                .eq(InsTaskStep::getTaskStartDate, DateUtils.now())
                                .eq(InsTaskStep::getStatus, InspectStepStatusEnum.CREATE.getCode())
                                .orderByAsc(InsTaskStep::getId));
            } else if (inspectType.equals(InspectTypeEnum.WEEK.getCode())) {

                List<LocalDateTime> localDateTimes = InspectDateUtil.getCurrentWeek(null);
                insTaskSteps = baseMapper
                        .selectList(new LambdaQueryWrapper<InsTaskStep>()
                                .eq(InsTaskStep::getTaskId, taskId)
                                .ge(InsTaskStep::getTaskStartDate, localDateTimes.get(0))
                                .le(InsTaskStep::getTaskEndDate, localDateTimes.get(1))
                                .orderByAsc(InsTaskStep::getId));

            } else if (inspectType.equals(InspectTypeEnum.MONTH.getCode())) {

                List<LocalDateTime> localDateTimes = InspectDateUtil.getCurrentMonth(null);

                insTaskSteps = baseMapper
                        .selectList(new LambdaQueryWrapper<InsTaskStep>()
                                .eq(InsTaskStep::getTaskId, taskId)
                                .ge(InsTaskStep::getTaskStartDate, localDateTimes.get(0))
                                .le(InsTaskStep::getTaskEndDate, localDateTimes.get(1))
                                .orderByAsc(InsTaskStep::getId));
            }
        } else {
            throw new RRException(RRExceptionEnum.TASK_NOT_EXIST);
        }
        return insTaskSteps;
    }

    @Override
    public int isBelong(Integer stepId, Integer userId) {

        int result = 2;
        InsTaskStep insTaskStep = baseMapper.selectById(stepId);
        if (insTaskStep.getExecutorId() != null && insTaskStep.getExecutorId().intValue() != userId) {
            result = 1;
        }
        return result;
    }

    @Override
    public InsTaskStep getAllById(Integer taskStepId) {
        return baseMapper.queryById(taskStepId);
    }

    @Override
    public List<InsMsgEntity> pushList() {
        return baseMapper.pushList();
    }

    @Override
    public void updatePushStatus(Integer taskId, String step) {

        List<InsTaskStep> insTaskSteps = baseMapper
                .selectList(new LambdaQueryWrapper<InsTaskStep>()
                        .eq(InsTaskStep::getTaskId, taskId)
                        .eq(InsTaskStep::getStep, step));
        insTaskSteps.forEach(insTaskStep -> {
            insTaskStep.setPushed(InsPushEnum.Y.getCode());
            this.updateById(insTaskStep);
        });

    }
}
